#include "Socket2.h"

Socket2::Socket2() {
    sock_fd = -1;
    connected = 0;
}

Socket2::~Socket2() {

}

int Socket2::open_s(const char *address, short port) {
    int ret = -1;
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);    //ipv4,TCP数据连接
    if (sock_fd < 0) {
        return ret;
    }
    bzero(&sa_server, sizeof(sa_server));
    sa_server.sin_family = AF_INET;
    sa_server.sin_port = htons(port);
    ret = -2;
    if (inet_pton(AF_INET, address, &sa_server.sin_addr) < 0) {    //set ip address
        close(sock_fd);
        sock_fd = -1;
        return ret;
    }
    strcpy(host, address);
    ret = connect(sock_fd, (struct sockaddr *) &sa_server, sizeof(sa_server)); //连接到服务器
    if (ret == 0) {
        connected = 1;
        struct timeval timeout = {0,200000};
        setsockopt(sock_fd, SOL_SOCKET,SO_SNDTIMEO, (char *)&timeout,sizeof(struct timeval));
        setsockopt(sock_fd, SOL_SOCKET,SO_RCVTIMEO, (char *)&timeout,sizeof(struct timeval));
    } else {
        close(sock_fd);
        sock_fd = -1;
    }
    return ret;
};

void Socket2::close_s() {
    shutdown(sock_fd, SHUT_RDWR);
    close(sock_fd);
    connected = 0;
    sock_fd = -1;
}

int Socket2::write_s(const char *buf, int size) {
    if (!connected) {
        return -1;
    }
    return send(sock_fd, buf, size, 0);
}

int Socket2::read_s(char *buff, int size) {
    if (!connected) {
        return -1;
    }
    return recv(sock_fd, buff, size, 0);
}
